package com.itheima.controller.system;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.store.Company;
import com.itheima.domain.system.Dept;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/system/dept/*")
public class DeptServlet extends BaseServlet {

    //查询所有
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        List<Dept> list=deptService.findAll(pageNum,pageSize);
        PageInfo<Dept> pageInfo=new PageInfo<Dept>(list);
       req.setAttribute("page",pageInfo);
       req.getRequestDispatcher("/pages/system/dept/list.jsp").forward(req,resp);
    }

    //获取不带分页信息的list(为了获取上级部门名称)
    private void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        List<Dept> list=deptService.list();
        ObjectMapper obj = new ObjectMapper();
        String json = obj.writeValueAsString(list);
        resp.getWriter().write(json);
    }
    //新增
    private void save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前新增对象并封装到dept中
        Map<String, String[]> map = req.getParameterMap();
        Dept dept = BeanUtil.fillBean(req, Dept.class);
        System.out.println(dept);
        //调用业务层新增方法
        deptService.save(dept);
        //新增完成后再次调用servlet查找所有方法
        findAll(req,resp);
    }
    //删除
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取要删除的ids(是个字符串,可以转成数组)
        String id = req.getParameter("ids");
        System.out.println(id);
        //调用业务层删除方法
        boolean flag=deptService.deleteByIds(id);
        if(flag){
            //删除成功则调用servlet查找所有方法
            findAll(req,resp);
        }else{
            //失败则跳转到错误页面
            req.getRequestDispatcher("/pages/error.jsp").forward(req,resp);
        }
    }
    //编辑第一次点击实际是根据id获取对象,并把id传给编辑框的对象
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取当前id
        String id = req.getParameter("id");
        Dept dept=deptService.findById(id);
        System.out.println(dept);
        req.setAttribute("dept",dept);
        req.getRequestDispatcher("/pages/system/dept/update.jsp").forward(req,resp);
    }

    //编辑
    private void update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取修改页面表单提交的数据，并封装到Company对象
        Dept dept = BeanUtil.fillBean(req, Dept.class);
        deptService.update(dept);
        findAll(req,resp);
    }
}
